import 'dart:async';
import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/page_under_creation.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/widgets/RotationImageWidget.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_apple_auth_storage/lib_apple_auth_storage.dart';
import 'package:lib_cloud_storage/lib_cloudstorage.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_network/lib_network.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/network/http_api.dart';
import '../../../module_common/network/http_chain_list.dart';
import '../../../module_common/network/http_encrypt.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/utils/auth.dart';
import '../../../module_common/utils/util.dart';
import '../../../module_common/widgets/header/page_header.dart';
import '../widgets/sheet/confirm_alert.dart';
import '../widgets/sheet/mpc_upload_sheet.dart';

enum MPCManagerPageType { Security, Recast }

//MPC分片的上传状态。 success:上传成功， faild:上传失败， normal:可点击， disable:不可用, again:重新, ing:正在进行
enum MPCStatus { success, faild, normal, disable, again, ing }

//MPC分片的上传类型。 server:服务器, local:本地, googleDrive:谷歌云, iCloud: 苹果云
enum MPCType { server, local, googleDrive, iCloud }

class WalletMPCSecurityManager extends StatefulWidget {
  MPCManagerPageType pageType;

  int? version;
  WalletMPCSecurityManager({Key? key, required this.pageType,this.version})
      : super(key: key);

  @override
  _WalletMPCSecurityManagerState createState() =>
      _WalletMPCSecurityManagerState();
}

class MPCModel {
  MPCType type;
  MPCStatus status;

  //扩展内容，一般是动态存的值，如：mpc分片
  String extension;

  //云端的地址路径
  String uploadPath;

  MPCModel(
      {required this.type,
      required this.status,
      this.extension = '',
      this.uploadPath = ''});

  @override
  String toString() {
    // TODO: implement toString
    return '{type :$type,extension:$extension,status:$status,uploadPath:$uploadPath}';
  }
}

class _WalletMPCSecurityManagerState extends State<WalletMPCSecurityManager> {
//创建展示的数据列表
  MPCModel serverInfo =
      MPCModel(type: MPCType.server, status: MPCStatus.normal);
  MPCModel localInfo = MPCModel(type: MPCType.local, status: MPCStatus.normal);
  MPCModel googleDriveInfo =
      MPCModel(type: MPCType.googleDrive, status: MPCStatus.normal);
  MPCModel iCloudInfo =
      MPCModel(type: MPCType.iCloud, status: MPCStatus.normal);
  bool _isPass = false;

  //是否正在展示loading框
  bool _isLoading = false;

  //
  bool _btnLoading = false;

  //初始化数据列表
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refreshStatus().then((value) {
      setState(() {});
    });
  }

  //重新刷新状态
  Future<void> refreshStatus() async {
    if (widget.pageType == MPCManagerPageType.Security) {
      //只需要检查本地有没有多片，有的话对应上传，所以不用检查云端
      var keyList = WalletCheck.getkeyList();
      switch (keyList.length) {
        case 1: //服务器与云端已上传
          localInfo.status = MPCStatus.success;
          serverInfo.status = MPCStatus.success;
          if (context.read<WalletInfoNotifier>().wallet!.googleFileId != null) {
            //已上传的话需要确认是上传了google还是iCloud
            googleDriveInfo.status = MPCStatus.success;
            iCloudInfo.status = MPCStatus.disable;
          }
          if (context.read<WalletInfoNotifier>().wallet!.appleFileId != null) {
            iCloudInfo.status = MPCStatus.success;
            googleDriveInfo.status = MPCStatus.disable;
          }
          break;
        case 2: //服务器已上传,云端未上传
          localInfo.status = MPCStatus.success;
          serverInfo.status = MPCStatus.success;
          break;
        case 3: //服务器未上传
          localInfo.status = MPCStatus.success;
          if (keyList[1].isEmpty) {
            //云端已上传
            if (context.read<WalletInfoNotifier>().wallet!.googleFileId !=
                null) {
              //已上传的话需要确认是上传了google还是iCloud
              googleDriveInfo.status = MPCStatus.success;
              iCloudInfo.status = MPCStatus.disable;
            }
            if (context.read<WalletInfoNotifier>().wallet!.appleFileId !=
                null) {
              iCloudInfo.status = MPCStatus.success;
              googleDriveInfo.status = MPCStatus.disable;
            }
          } else {
            //云端未上传
          }
          break;
        default:
          break;
      }
      //最后在这里检查一下。观察钱包 本地必定没有分片
      if (context.read<WalletInfoNotifier>().wallet!.type == 2) {
        localInfo.status = MPCStatus.faild;
      } else if (context.read<WalletInfoNotifier>().wallet!.type == 3) {
        localInfo.status = MPCStatus.success;
      }
    } else {
      //重铸页面,让用户自己点击获取分片
      if (context.read<WalletInfoNotifier>().wallet!.type == 2) {
        //观察钱包 本地必定没有分片
        localInfo.status = MPCStatus.faild;
      } else if (context.read<WalletInfoNotifier>().wallet!.type == 3) {
        localInfo.status = MPCStatus.success;
        List<String> keyList = WalletCheck.getkeyList();
        localInfo.extension = keyList.length > 0 ? keyList[0] : '';
      }

      serverInfo.status = MPCStatus.normal;
      kaiPrint('NativeChannelBridge.instance.appCommMsg!.google_email ${NativeChannelBridge.instance.appCommMsg!.google_email}');
      if (NativeChannelBridge.instance.appCommMsg!.google_email == null ||
          NativeChannelBridge.instance.appCommMsg!.google_email!.isEmpty) {
        googleDriveInfo.status = MPCStatus.disable;
      } else {
        googleDriveInfo.status = MPCStatus.normal;
      }
      kaiPrint('googleDriveInfo.status ${googleDriveInfo.status}');

      if (NativeChannelBridge.instance.appCommMsg!.apple_user_id == null ||
          NativeChannelBridge.instance.appCommMsg!.apple_user_id!.isEmpty) {
        iCloudInfo.status = MPCStatus.disable;
      } else {
        iCloudInfo.status = MPCStatus.normal;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageHeaderCom(
            title: widget.pageType == MPCManagerPageType.Security
                ? 'MPC Security Management'
                : (widget.version==1?'Upgrade wallet':'Recast Wallet'),
            showBottomBorder: false),
        body: Padding(
          padding: EdgeInsets.only(left: 20.w, right: 20.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 10.w),
              row(model: serverInfo),
              SizedBox(height: 10.w),
              row(model: localInfo),
              SizedBox(height: 20.w),
              Text(
                'Cloud',
                style: TextStyle(
                    fontSize: 14,
                    color: '#333333'.toColor(),
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10.w),
              row(model: googleDriveInfo),
              SizedBox(height: 15.w),
              Visibility(
                  visible: Platform.isIOS &&
                      NativeChannelBridge
                              .instance.appCommMsg!.isAppleEnterprise ==
                          false,
                  child: row(model: iCloudInfo)),
              SizedBox(height: 20.w),
              Expanded(child: Container()),
              Visibility(
                visible: widget.pageType == MPCManagerPageType.Recast,
                child: PublicButton(
                  text: 'Reconstruct',
                  margin: null,
                  type: ButtonType.private,
                  disabledStatus: !checkCanReconstruct(),
                  onClick: () {
                    if (_isLoading) {
                      return;
                    }
                    _isLoading = true;
                    if (checkCanReconstruct()) {
                      reconstructMPC().then((value) {
                        if (value == false) {
                          _isLoading = false;
                        }
                      });
                    }
                  },
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).padding.bottom + 10,
              )
            ],
          ),
        ));
  }

  /////////////////////////////////////////////UI展示/////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////
  Widget row({required MPCModel model}) {
    return Container(
      height: 60.w,
      decoration: BoxDecoration(
        border: Border.all(color: "#E0E0E0".toColor()),
        borderRadius: BorderRadius.circular(10),
        gradient: gradient(model.status),
      ),
      child: Row(
        children: [
          Padding(
              padding: EdgeInsets.only(left: 15.w, right: 10.w),
              child: typeImage(model.type)),
          Expanded(
              child: Text(
            typeTitle(model.type),
            style: TextStyle(
                fontSize: 14,
                color: '#333333'.toColor(),
                fontWeight: FontWeight.w500),
          )),
          rightWidget(model.type, model.status)
        ],
      ),
    );
  }

  Widget typeImage(MPCType type) {
    String imgPath = '';
    switch (type) {
      case MPCType.server:
        imgPath = 'assets/images/wallet/upload_server.png';
        break;
      case MPCType.local:
        imgPath = 'assets/images/wallet/upload_local.png';
        break;
      case MPCType.googleDrive:
        imgPath = 'assets/images/wallet/upload_googledrive.png';
        break;
      case MPCType.iCloud:
        imgPath = 'assets/images/wallet/upload_icloud.png';
        break;
    }

    return Image.asset(imgPath, width: 20.w, height: 20.w);
  }

  //对应类型的title
  String typeTitle(MPCType type) {
    switch (type) {
      case MPCType.server:
        return 'Server';
      case MPCType.local:
        return 'Local';
      case MPCType.googleDrive:
        return 'Google Drive';
      case MPCType.iCloud:
        return 'iCloud';
    }
  }

  //根据状态返回背景颜色
  Gradient? gradient(MPCStatus status) {
    switch (status) {
      case MPCStatus.success:
        return LinearGradient(
          colors: ["#FBFBFB".toColor(), '#F0FFFC'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.faild:
        return LinearGradient(
          colors: ["#FFFFFF".toColor(), '#FFF3F1'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.again:
        return LinearGradient(
          colors: ["#FFFFFF".toColor(), '#FFFAEA'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.normal:
        return null;
      case MPCStatus.ing:
        return null;
      case MPCStatus.disable:
        return null;
    }
  }

  //根据状态返回右边视图
  Widget rightWidget(MPCType type, MPCStatus status) {
    switch (status) {
      case MPCStatus.success:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: Image.asset(
            'assets/images/dapp/success.png',
            width: 20.w,
            height: 20.w,
          ),
        );
      case MPCStatus.faild:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: Image.asset(
            'assets/images/dapp/error.png',
            width: 20.w,
            height: 20.w,
          ),
        );
      case MPCStatus.again:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(top: 7.w, bottom: 7.w),
              height: 30,
              width: 70,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.w),
                  color: '#FFA41A'.toColor()),
              child: Image.asset(
                'assets/images/wallet/refresh.png',
                fit: BoxFit.fitHeight,
              ),
            ),
            onTap: () {
              //上传、下载分片
              clickBtn(type);
            },
          ),
        );
      case MPCStatus.normal:
        return rightButton(type, status);
      case MPCStatus.ing:
        return rightButton(type, status);
      case MPCStatus.disable:
        return rightButton(type, status);
    }
  }

  Widget rightButton(MPCType type, MPCStatus status) {
    bool isLoading = status == MPCStatus.ing;
    bool disabledStatus = isLoading || status == MPCStatus.disable;
    bool isGet = widget.pageType == MPCManagerPageType.Recast;

    return Container(
        width: 70.w,
        margin: EdgeInsets.only(left: 10.w, right: 15.w),
        child: PublicButton(
          image: isLoading && isGet ? rotation() : null,
          radius: 4.w,
          margin: null,
          text: isGet ? 'GET' : 'Upload',
          height: 30.w,
          disabledStatus: disabledStatus,
          type: ButtonType.private,
          onClick: () {
            if (status == MPCStatus.disable) {
              kaiPrint('---------');
            } else {
              //上传、下载分片
              clickBtn(type);
            }
          },
        ));
  }

  Widget rotation() {
    return RotationImage(
        image: Image.asset('assets/images/wallet/downloading.png',
            width: 16.w, height: 16.w));
  }

  //检查能不能重铸
  bool checkCanReconstruct() {
    var mpcCount = 0;
    if (serverInfo.status == MPCStatus.success) {
      mpcCount += 1;
    }
    if (localInfo.status == MPCStatus.success) {
      mpcCount += 1;
    }
    if (googleDriveInfo.status == MPCStatus.success ||
        iCloudInfo.status == MPCStatus.success) {
      mpcCount += 1;
    }

    return mpcCount >= 2;
  }

  /////////////////////////////////////////////点击事件/////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////////////////////
  Future<void> clickBtn(MPCType type) async {
    if (widget.pageType == MPCManagerPageType.Security) {
      //这里都是上传
      switch (type) {
        case MPCType.server:
          _serverUpload();
          break;
        case MPCType.googleDrive:
          //判断是否绑定
          if (NativeChannelBridge.instance.appCommMsg!.google_email == null ||
              NativeChannelBridge.instance.appCommMsg!.google_email!.isEmpty) {
            GoogleLoginResult req = await LibCloudStorage.startGoogleLogin();
            if (req.email.isEmpty) {
              Toast.show(context, message: 'Google auth fail', status: '0');
              return;
            }

            //通知通道更新数据
            var params = {
              "email": req.email,
              "device_type":
                  NativeChannelBridge.instance.appCommMsg!.device_type,
              'id_token': req.idToken
            };

            var resp = await HttpManager().post(API.authGoogle, params);
            //1157为已绑定
            if (resp!.code == HttpConfig().successCode) {
              NativeChannelBridge.instance.appCommMsg?.google_email = req.email;

              googleUpload(type);
            } else if (resp.code == 1157) {
              //已经被其他人绑定了
              Toast.show(context, message: resp.msg, status: '0');
            } else {
              Toast.show(context, message: resp.msg, status: '0');
            }
            return;
          } else {
            GoogleLoginResult req = await LibCloudStorage.startGoogleLogin();
            if (req.email.isEmpty) {
              Toast.show(context, message: 'Google auth fail', status: '0');
              return;
            }
            if (req.email ==
                NativeChannelBridge.instance.appCommMsg!.google_email) {
              googleUpload(type);
            } else {
              Toast.show(context,
                  message:
                      'Please upload to the Google account linked to ${NativeChannelBridge.instance.appCommMsg!.google_email}',
                  status: '0');
            }
          }

          break;
        case MPCType.iCloud:
          clickAppleUpload(type);

          break;
        default:
          break;
      }
    } else {
      ////////////////////////这里都是下载////////////////////////
      switch (type) {
        case MPCType.server:
          _serverDownLoad();

        case MPCType.googleDrive:
          _googleDownLoad();
          break;
        case MPCType.iCloud:
          _iCloudDownLoad();
          break;
        default:
      }
    }
  }

  void googleUpload(MPCType type) {
    var pk = getPK(type);
    if (pk.isEmpty) {
      Toast.show(context, message: 'pk lose', status: '0');
      return;
    }

    Utils.showBottomSheetDialog(
        context,
        WalletMPCUploadSheet(
          pk: pk,
          type: type,
          callback: (status) {
            if (mounted)
              setState(() {
                if (status == MPCStatus.success) {
                  iCloudInfo.status = MPCStatus.disable;
                }
                googleDriveInfo.status = status;
              });
          },
        ));
  }

  void clickAppleUpload(MPCType type) async {
    showDialog(
      useSafeArea: false,
      context: context,
      builder: (contextDialog) {
        return MyDialog(
          title: 'Important-Note',
          detail:
              'After uploading the shards to iCloud, switching to an Android device will result in the inability to retrieve the shard keys. Please take note!',
          onConfirm: () async {
            //关闭当前的提示框
            Navigator.of(contextDialog).pop();

            if (NativeChannelBridge.instance.appCommMsg!.apple_user_id ==
                    null ||
                NativeChannelBridge
                    .instance.appCommMsg!.apple_user_id!.isEmpty) {
              var req = await LibAppleAuthStorage.login();
              if (req == null) {
                Toast.show(context, message: 'apple auth fail', status: '0');
                return;
              }

              //通知通道更新数据
              var params = {
                "apple_id": req.userID,
                'identity_token': req.idToken
              };

              var resp = await HttpManager().post(API.authApple, params);
              if (resp!.code == HttpConfig().successCode) {
                NativeChannelBridge.instance.appCommMsg!.apple_user_id =
                    req.userID;

                appleUpload(type);
              } else if (resp.code == 1053) {
                //已经被其他人绑定了
                Toast.show(context, message: resp.msg, status: '0');
              } else {
                Toast.show(context, message: resp.msg, status: '0');
              }
              return;
            } else {
              var req = await LibAppleAuthStorage.login();
              if (req == null) {
                Toast.show(context, message: 'apple auth fail', status: '0');
                return;
              }
              //如果绑定的id和原本原生穿过来的不一致，要提示使用一致的来绑定
              if (req.userID ==
                  NativeChannelBridge.instance.appCommMsg!.apple_user_id) {
                // Navigator.of(context).pop();
                appleUpload(type);
              } else {
                Toast.show(context,
                    message:
                        'Please upload to the Apple ID account linked to ${req.userID}',
                    status: '0');
              }
            }
          },
        );
      },
    );
  }

  void appleUpload(MPCType type) {
    var pk = getPK(type);
    if (pk.isEmpty) {
      Toast.show(context, message: 'pk lose', status: '0');
      return;
    }

    Utils.showBottomSheetDialog(
        context,
        WalletMPCUploadSheet(
          pk: pk,
          type: MPCType.iCloud,
          callback: (status) {
            if (mounted)
              setState(() {
                if (status == MPCStatus.success) {
                  googleDriveInfo.status = MPCStatus.disable;
                }
                iCloudInfo.status = status;
              });
          },
        ));
  }

  String getPK(MPCType type) {
    try {
      var keyList = WalletCheck.getkeyList();

      switch (type) {
        case MPCType.server:
          if (keyList.length == 3) {
            //只有三个的情况才是服务器分片没上传
            return keyList[2];
          }

        case MPCType.googleDrive:
          if (keyList.length == 3 || keyList.length == 2) {
            //三片的情况第二个为云端分片, 只有两片的情况，第二片时云端分片。
            return keyList[1];
          }
        case MPCType.iCloud:
          if (keyList.length == 3 || keyList.length == 2) {
            //三片的情况第二个为云端分片, 只有两片的情况，第二片时云端分片。
            return keyList[1];
          }
        case MPCType.local:
          return keyList.first;
      }
      return '';
    } catch (e) {
      return '';
    }
  }

  //上传后台
  Future<void> _serverUpload({String? pk = null}) async {
    var key = pk ?? getPK(MPCType.server);

    try {
      if (key.isEmpty) {
        kaiPrint('key = null  return');
        return;
      }
      // 上传服务器直接 成功 才生成 钱包
      Map<String, dynamic> params = {'cover': 0,'mpcSalt': key};
      var resp = await HttpManager().post(API.uploadOnePiece, params);
      if (resp?.code != HttpConfig().successCode) {
        throw Exception('Failed to upload private key.');
      }

      if (resp!.data['result'] == false) {
        throw Exception('Failed to upload private key.');
      }
      Map<String, dynamic> paramsSalt = {
        'mpcSalt': context.read<WalletInfoNotifier>().wallet!.salt.toString(),
      };
      var result = await HttpManager().post(API.uploadMpcSalt, paramsSalt);
      if (resp.code != HttpConfig().successCode) {
        throw Exception('Failed to upload salt.');
      }

      if (result!.data['isUpload'] == false) {
        throw Exception('Failed to upload salt.');
      }

      //上传服务器成功，删除服务器分片
      context.read<WalletInfoNotifier>().updateWalletServer();

      serverInfo.status = MPCStatus.success;
    } catch (e) {
      kaiPrint(e);
      return;
    } finally {
      if (mounted) setState(() {});
    }
  }

  //服务器下载分片
  _serverDownLoad() async {
    if (mounted)
      setState(() {
        serverInfo.status = MPCStatus.ing;
      });
    try {
      WalletCheck.getServerKey().then((mpc) {
        switch (mpc.$2) {
          case authGetDocStatus.success:
            serverInfo.extension = mpc.$1;
            serverInfo.status = MPCStatus.success;
            break;
          case authGetDocStatus.emailEmpty:
            serverInfo.status = MPCStatus.again;
            break;
          case authGetDocStatus.emailNotEqual:
            serverInfo.status = MPCStatus.again;
            break;
          case authGetDocStatus.noData:
            serverInfo.status = MPCStatus.faild;
            break;
          default:
        }

        if (mounted) setState(() {});
      });
    } catch (e) {
      serverInfo.status = MPCStatus.again;
      if (mounted) setState(() {});
    }
  }

  //从google下载分片
  _googleDownLoad() {
    if (_btnLoading) {
      return;
    }
    _btnLoading = true;
    if (mounted) {
      setState(() {
        googleDriveInfo.status = MPCStatus.ing;
      });
    }

    try {
      WalletCheck.getGoogleKey().then((mpc) {
        switch (mpc.$3) {
          case authGetDocStatus.success:
            googleDriveInfo.extension = mpc.$1;
            googleDriveInfo.uploadPath = mpc.$2;
            googleDriveInfo.status = MPCStatus.success;
            iCloudInfo.status = MPCStatus.disable;
            break;
          case authGetDocStatus.emailEmpty:
            googleDriveInfo.status = MPCStatus.again;

            break;
          case authGetDocStatus.emailNotEqual:
            Toast.show(context,
                message:
                    'Please select the account ${NativeChannelBridge.instance.appCommMsg!.google_email} to retrieve the shard data.',
                status: '0');

            googleDriveInfo.status = MPCStatus.again;
            break;
          case authGetDocStatus.noData:
            googleDriveInfo.status = MPCStatus.faild;

            break;
          case authGetDocStatus.cancel:
            Toast.show(context,
                message:
                    'Authorization failed. Enable required Google permissions.',
                status: '2');
            googleDriveInfo.status = MPCStatus.again;

            break;
        }

        _btnLoading = false;
        if (mounted) setState(() {});
      });
    } catch (e) {
      kaiPrint('_googleDownLoad error: $e');
      googleDriveInfo.status = MPCStatus.again;
      _btnLoading = false;
      if (mounted) setState(() {});
    }
  }

  //iCloud下载，返回是否成功下载
  _iCloudDownLoad() async {
    if (_btnLoading) {
      return;
    }
    _btnLoading = true;
    if (mounted)
      setState(() {
        iCloudInfo.status = MPCStatus.ing;
      });
    try {
      WalletCheck.getIcloudKey().then((mpc) {
        switch (mpc.$2) {
          case authGetDocStatus.success:
            iCloudInfo.extension = mpc.$1;
            String uid = NativeChannelBridge.instance.appCommMsg!.userId;
            String salt = SP().getRandomSalt() ?? '';
            iCloudInfo.uploadPath = '${uid}_${salt}';
            iCloudInfo.status = MPCStatus.success;
            googleDriveInfo.status = MPCStatus.disable;
            break;
          case authGetDocStatus.emailEmpty:
            iCloudInfo.status = MPCStatus.again;
            break;
          case authGetDocStatus.emailNotEqual:
            Toast.show(context,
                message:
                    'Please select the account ${NativeChannelBridge.instance.appCommMsg!.apple_user_id} to retrieve the shard data.',
                status: '0');

            iCloudInfo.status = MPCStatus.again;
            break;
          case authGetDocStatus.noData:
            iCloudInfo.status = MPCStatus.faild;
            break;
          case authGetDocStatus.cancel:
            Toast.show(context,
                message:
                    'Authorization failed. Enable required Apple ID permissions.',
                status: '2');
            iCloudInfo.status = MPCStatus.again;
            break;
        }
        _btnLoading = false;
        if (mounted) setState(() {});
      });
    } catch (e) {
      iCloudInfo.status = MPCStatus.again;
      _btnLoading = false;
      if (mounted) setState(() {});
    }
  }

//重铸
  Future<bool> reconstructMPC() async {
    try {
      // 在某个时刻手动完成 Future
      // 判断没 设置密码
      bool isSetPass = ObjectBox()
          .userSettingsModel
          .isPasswordSet(NativeChannelBridge.instance.appCommMsg!.userId);

      if (!isSetPass) {
        // 关闭当前 页面
        Toast.show(context,
            message: "Please set a password first！", status: '0');
        return false;
      }
      if (!_isPass) {
        _isPass = await Authentication().startLocalAuth(
            showPasswordError: false,
            callBackError: () {
              Toast.show(context,
                  status: '0',
                  position: Dpositon.top,
                  message: "Verification password error",
                  duration: Duration(milliseconds: 3000));
            });
      }
      if (!_isPass) return false;
      Navigator.of(context)
          .push(MaterialPageRoute(
              builder: (context) => PageUnderCreation(
                    type: widget.version ==1 ?WalletCreationType.OVERWRITE :WalletCreationType.RECAST,
                    version: widget.version,
                    callBack: () async {
                      try {
                        walletErrorStatus errorStatus =
                            walletErrorStatus.localError;
                        if (serverInfo.status == MPCStatus.faild) {
                          errorStatus = walletErrorStatus.serverError;
                        }
                        if (localInfo.status == MPCStatus.faild) {
                          errorStatus = walletErrorStatus.localError;
                        }
                        if (googleDriveInfo.status == MPCStatus.faild) {
                          errorStatus = walletErrorStatus.googleError;
                        }
                        if (Platform.isIOS &&
                            iCloudInfo.status == MPCStatus.faild) {
                          errorStatus = walletErrorStatus.icloudError;
                        }

                        List<String> pieceList = [];
                        if (serverInfo.extension.isNotEmpty) {
                          pieceList.add(serverInfo.extension);
                        }
                        if (localInfo.extension.isNotEmpty) {
                          pieceList.add(localInfo.extension);
                        }
                        if (googleDriveInfo.extension.isNotEmpty) {
                          pieceList.add(googleDriveInfo.extension);
                        } else if (iCloudInfo.extension.isNotEmpty) {
                          pieceList.add(iCloudInfo.extension);
                        }
                        String? newPiece = null;
                        // var localSalt = await SP().getRandomSalt();
                        if(widget.version==1){
                          //算法重铸出第三片分片
                          return pieceList;
                        }else {
                          //算法重铸出第三片分片
                         newPiece = await mpcTool()
                              .recoverMPCFragment(pieceList[0], pieceList[1]);
                         kaiPrint('newPiece $newPiece');
                         kaiPrint('newPiece :::::::::: ${newPiece.length}');
                        }
                        if (newPiece == null || newPiece.isEmpty) {
                          Toast.show(context,
                              message:
                                  'Recasting failed due to cloud shard synthesis exception.',
                              status: '0');
                          return [];
                        }
                        //拿到后重新刷新钱包
                        switch (errorStatus) {
                          case walletErrorStatus.serverError:
                            await _reconstructMPC_upload_server(newPiece);
                            break;
                          case walletErrorStatus.localError:
                            await _reconstructMPC_upload_local(newPiece);
                            break;
                          case walletErrorStatus.googleError:
                            await _reconstructMPC_upload_google(newPiece);
                            break;
                          case walletErrorStatus.icloudError:
                            await _reconstructMPC_upload_icloud(newPiece);
                            break;
                          default:
                            break;
                        }
                        return pieceList;
                      } catch (e) {
                        kaiPrint('PageUnderCreation  $e');
                        return [];
                      }
                    },
                  )))
          .then((value) {
        _isLoading = false;
        if (value == 'Success') {
          Navigator.of(context).pop();
          Toast.show(context, message: (widget.version==1?'Upgrade wallet':'Recast Wallet')+' successfully');
          return;
        }
      });
      kaiPrint('reconstructMPC  false');
      return true;
    } catch (e) {
      kaiPrint(e);
      return false;
    }
  }

  Future<void> _reconstructMPC_upload_server(String newPiece) async {
    await _serverUpload(pk: newPiece);
  }

  Future<void> _reconstructMPC_upload_local(String newPiece) async {
    kaiPrint('_reconstructMPC_upload_local ::::; ${newPiece.length}');
    //如果是本地分片处理好了，那就重新处理钱包
    await _upload_local_provider(newPiece);
    // EasyLoading.generateLoadingFuture(,
    //         status: 'New device found Regenerating shards for you')
    //     .then((value) async {
    //   ///还要更新对应位置的分片
    // });
  }

  _upload_local_provider(String newPiece) {
    try {
      kaiPrint('context.read<WalletInfoNotifier>().wallet :::::: ${context.read<WalletInfoNotifier>().wallet}');
      //更新钱包
      ObjectBox().walletModel.updateWalletType(
          context.read<WalletInfoNotifier>().wallet, 3, newPiece.trim());


      kaiPrint('context.read<WalletInfoNotifier>().wallet222222 :::::: ${context.read<WalletInfoNotifier>().wallet}');
      context
          .read<WalletInfoNotifier>()
          .updateCurrentWallet(context.read<WalletInfoNotifier>().walletInfo!);

      //这里重铸后，要通知是云端哪里获取的
      if (googleDriveInfo.extension.isNotEmpty) {
        context
            .read<WalletInfoNotifier>()
            .updateWalletGoogleFileId(googleDriveInfo.uploadPath);
      } else if (iCloudInfo.extension.isNotEmpty) {
        context
            .read<WalletInfoNotifier>()
            .updateWalletAppleFileId(iCloudInfo.uploadPath);
      }
    } catch (e) {
      kaiPrint(e);
    }
  }

  Future<void> _reconstructMPC_upload_google(String newPiece) async {
    String uid = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    String email = NativeChannelBridge.instance.appCommMsg?.google_email ?? '';
    String salt = SP().getRandomSalt() ?? "";
    try{
      // 判断 盐 服务端盐 是否真是存在
      String? serverKey = (await WalletCheck.getServerKey()).$1;
      kaiPrint('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
      if(serverKey.isNotEmpty){
        salt = await HttpChainList().getSaltByUrl()??'';
        kaiPrint('_reconstructMPC_upload_google salt $salt');
      }
    }catch(e){
      kaiPrint(' $e');
    }
    String fileID =
        await LibCloudStorage.uploadToGoogleCloud(email, newPiece, uid, salt);
    context.read<WalletInfoNotifier>().updateWalletGoogleFileId(fileID);
  }

  Future<void> _reconstructMPC_upload_icloud(String newPiece) async {
    String uid = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    String salt = SP().getRandomSalt() ?? "";
    try{
      // 判断 盐 服务端盐 是否真是存在
      String? serverKey = (await WalletCheck.getServerKey()).$1;
      kaiPrint('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
      if(serverKey.isNotEmpty){
        salt = await HttpChainList().getSaltByUrl()??'';
        kaiPrint('_reconstructMPC_upload_icloud salt $salt');
      }
    }catch(e){
      kaiPrint('$e');
    }
    await LibAppleAuthStorage.storage(uid, newPiece, salt);
    context
        .read<WalletInfoNotifier>()
        .updateWalletAppleFileId('${uid}_${salt}');
  }
}
